package com.xunyun.kotlinwc.network

import android.util.Log
import com.xunyun.kotlinwc.network.interceptor.SignInterceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit

/**
 * @author gl
 * @date 2021/9/7
 * @desc
 */
class RetrofitHolder {
    private var retrofit: Retrofit? = null

    companion object {
        const val BASE_URL: String = "https://www.wanandroid.com/";
        const val CONNECT_TIME_OUT = 30L
        const val READ_TIME_OUT = 30L
        const val WRITE_TIME_OUT = 30L
        val singleton = Instance.holder
    }

    private object Instance {
        val holder = RetrofitHolder()
    }

    fun getRetrofit(): Retrofit {
        if (null == retrofit) {
            return createRetrofit();
        }
        return retrofit as Retrofit;
    }

    private fun createRetrofit(): Retrofit {

        return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .addConverterFactory(ScalarsConverterFactory.create())
            .client(getOkHttpClient())
            .build();
    }

    private fun getOkHttpClient(): OkHttpClient {
        val logging = HttpLoggingInterceptor { message -> Log.e("OkHttpClient", message) }
        logging.apply { logging.level = HttpLoggingInterceptor.Level.BASIC }
        return OkHttpClient.Builder()
            .addInterceptor(logging)
            .addInterceptor(SignInterceptor())
            .connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS)
            .writeTimeout(WRITE_TIME_OUT, TimeUnit.SECONDS)
            .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS)
            .build();
    }
}